package com.cloud.media.api.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.cloud.media.common.result.FileInfo;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.media.api.entity.Media;
import com.cloud.media.api.mapper.MediaMapper;
import com.cloud.media.api.service.MediaService;
import com.cloud.media.common.consts.MediaConsts;
import com.cloud.media.common.utils.DateHelper;
import com.cloud.media.common.utils.RedisKeyHelper;
import com.cloud.media.common.utils.SessionHelper;
import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class MediaServiceImpl implements MediaService {

	@Autowired
	private MediaMapper mediaMapper;

	@Override
	public Media upload(MultipartFile file, String basePath, String mediaCatalog) {
		long mediaId = RedisKeyHelper.genereateKey(Media.class);
		// 文件保存路径 /egova/MediaRoot/attachment/2019/01/01/1_xxxx.doc
		if(StringUtils.isEmpty(mediaCatalog)){
			mediaCatalog = MediaConsts.MEDIA_CATALOG_ATTACHMENT;
		}
		Date now = new Date();
		StringBuilder filePath = new StringBuilder()
				.append(mediaCatalog).append(File.separator)
				.append(DateHelper.dateToFormatStr(now, "yyyy")).append(File.separator)
				.append(DateHelper.dateToFormatStr(now, "MM")).append(File.separator)
				.append(DateHelper.dateToFormatStr(now, "dd")).append(File.separator).append(mediaId).append("_")
				.append(file.getOriginalFilename());
		File f = new File(basePath + filePath.toString());
		try {
			FileUtils.writeByteArrayToFile(f, file.getBytes());
		} catch (Exception e) {
			throw new RuntimeException("文件上传失败", e);
		}
		Media media = new Media();
		media.setMediaId(mediaId);
		String fileName = file.getOriginalFilename();
		media.setMediaName(fileName);
		String[] c = fileName.split("[.]");
		String mediaType = "";
		if(c.length > 1){
			mediaType = c[c.length - 1].toUpperCase();
		}
		media.setMediaType(mediaType);
		media.setMediaPath(filePath.toString());
		media.setUploadTime(now);
		media.setUploadUser(SessionHelper.get().getHumanName());
		mediaMapper.insert(media);
		return media;
	}

	@Override
	public byte[] download(long mediaId) {
		Media media = mediaMapper.selectByPrimaryKey(mediaId);
		byte[] fileContent = null;
		try {
			fileContent = FileUtils.readFileToByteArray(new File(media.getMediaPath()));
		} catch (IOException e) {
			throw new RuntimeException("文件下载失败", e);
		}
		return fileContent;
	}

	@Override
	public Media loadMedia(long mediaId) {
		return mediaMapper.selectByPrimaryKey(mediaId);
	}

	@Override
	public List<Media> getAllMediaByIds(List<String> ids) {
		Example example = new Example(Media.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andIn("mediaId", ids);
		return mediaMapper.selectByExample(example);
	}

	@Override
	public List<Media> getUrlById(List<Long> ids) {
		Example example = new Example(Media.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andIn("mediaId", ids);
		return mediaMapper.selectByExample(example);
	}

	@Override
	public Media autoUpload(byte[] file, String basePath, String mediaCatalog) {
		long mediaId = RedisKeyHelper.genereateKey(Media.class);
		// 文件保存路径 /egova/MediaRoot/attachment/2019/01/01/1_xxxx.doc
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String name = "执法监督数据汇总" + sdf.format(new Date()) + ".xlsx";
		if(StringUtils.isEmpty(mediaCatalog)){
			mediaCatalog = MediaConsts.MEDIA_CATALOG_ATTACHMENT;
		}
		Date now = new Date();
		StringBuilder filePath = new StringBuilder()
				.append(mediaCatalog).append(File.separator)
				.append(DateHelper.dateToFormatStr(now, "yyyy")).append(File.separator)
				.append(DateHelper.dateToFormatStr(now, "MM")).append(File.separator)
				.append(DateHelper.dateToFormatStr(now, "dd")).append(File.separator).append(mediaId).append("_")
				.append(name);
		File f = new File(basePath + filePath.toString());
		try {
			FileUtils.writeByteArrayToFile(f, file);
		} catch (Exception e) {
			throw new RuntimeException("文件上传失败", e);
		}
		Media media = new Media();
		media.setMediaId(mediaId);
		String fileName = name;
		media.setMediaName(fileName);
		String[] c = fileName.split("[.]");
		String mediaType = "";
		if(c.length > 1){
			mediaType = c[c.length - 1].toUpperCase();
		}
		media.setMediaType(mediaType);
		media.setMediaPath(filePath.toString());
		media.setUploadTime(now);
		media.setUploadUser("超级管理员");
		mediaMapper.insert(media);
		return media;
	}

	@Override
	public List<FileInfo> getFileInfo(){
		List<FileInfo> list = new ArrayList<FileInfo>();
		String path = MediaConsts.DEFAULT_MEIDA_ROOT + MediaConsts.MEDIA_CATALOG_RESOURCE;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar cal = Calendar.getInstance();
		File file = new File(path);
		File[] tempList = file.listFiles();
		if (tempList != null) {
			if (tempList.length > 0) {
				for (int i = 0; i < tempList.length; i++) {
					FileInfo fileInfo = new FileInfo();
					if (tempList[i].isFile()) {
						// 获取文件名称
						String[] name = tempList[i].getName().split("\\.");
						fileInfo.setName(name[0]);
						// 文件类型
						fileInfo.setType(name[1]);
						long time = tempList[i].lastModified();
						cal.setTimeInMillis(time);
						// 文件修改时间
						fileInfo.setUploadTime(formatter.format(cal.getTime()));
						// 文件大小
						fileInfo.setSize(FormetFileSize(tempList[i].length()));
						list.add(fileInfo);
					}
				}
			}
		}
		return list;
	}

	public String FormetFileSize(long fileS) {
		DecimalFormat df = new DecimalFormat("#.00");
		DecimalFormat d = new DecimalFormat("#");
		String fileSizeString = "";
		if(fileS < 1024){
			fileSizeString = d.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) +"GB";
		}
		return fileSizeString;
	}

}
